import {
  AfterViewInit,
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  ElementRef,
  OnInit,
  TemplateRef,
  ViewChild, ViewEncapsulation,
} from '@angular/core';
import {MessageService} from '../../core/services/common/message.service';
import {NzMessageService} from "ng-zorro-antd/message";
import JsBarcode from 'jsbarcode';
import {MyTableConfig} from "../../share/components/ant-table/ant-table.component";
import {ContractLabel, OptionsInterface, SearchCommonVO} from "../../core/services/types";
import {NzTableQueryParams} from "ng-zorro-antd/table";
import {FileManageService} from "../../core/services/http/file-manage.service";
import FileSaver from "file-saver";
import {ModalBtnStatus} from "../../widget/base-modal";
import {NzModalService} from "ng-zorro-antd/modal";
import {FileManageModalService} from "../../widget/biz-widget/file-manage-modal/file-manage-modal.service";
import {NzNotificationService} from 'ng-zorro-antd/notification';

interface SearchParam {
  projectNum: string;
  client: string;
  projectContent: string;
  evaluatePerson: string;
  typeId: string;
}

@Component({
  selector: 'app-file-manage',
  templateUrl: './file-manage.component.html',
  styleUrls: ['./file-manage.component.less'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  encapsulation: ViewEncapsulation.None
})
export class FileManageComponent implements OnInit, AfterViewInit {
  isCollapse = false;
  searchParam: Partial<SearchParam> = {};
  id!: any;
  uid!: any;
  @ViewChild('dataDetail', {static: false}) template?: TemplateRef<{}>;
  @ViewChild('operationTpl', {static: true}) operationTpl!: TemplateRef<any>;
  @ViewChild('repertoryFlagTpl', {static: true}) repertoryFlagTpl!: TemplateRef<any>;
  @ViewChild('lendFlagTpl', {static: true}) lendFlagTpl!: TemplateRef<any>;
  @ViewChild('myInput', {static: true}) myInput!: ElementRef;
  @ViewChild('dragTpl', {static: true}) dragTpl!: TemplateRef<any>;
  tableConfig!: MyTableConfig;
  dataList: ContractLabel[];
  detailData: ContractLabel;
  checkedCashArray: ContractLabel[] = [];
  Options!: OptionsInterface[];

  constructor(private messageService: MessageService, private msg: NzMessageService, private modalSrv: NzModalService,
              private cdr: ChangeDetectorRef, private dataService: FileManageService,
              private modalService: FileManageModalService, private notification: NzNotificationService) {
    this.dataList = [];
    this.detailData = {
      projectNum: '',
      client: '',
      projectContent: '',
      signPerson: '',
      storageTime: new Date(),
      evaluatePerson: '',
      startTaskTime: new Date(),
      remark: '',
      typeName: '',
    };
  }

  selectedChecked(e: any): void {
    this.checkedCashArray = [...e];
  }

  resetForm(): void {
    this.searchParam = {};
    this.getDataList();
  }

  getDataList(e?: NzTableQueryParams): void {
    this.tableConfig.loading = true;
    const params: SearchCommonVO<any> = {
      pageSize: this.tableConfig.pageSize!,
      pageNum: e?.pageIndex || this.tableConfig.pageIndex!,
      filters: this.searchParam!
    };
    this.dataService.getLabelList(params).subscribe((data => {
      const {list, total, pageNum} = data;
      this.dataList = [...list];
      this.tableConfig.total = total!;
      this.tableConfig.pageIndex = pageNum!;
      this.tableLoading(false);
    }));
  }

  toJsBarcode(id: number) {
    JsBarcode('#svgcode', "0" + String(id), {
      format: "CODE39",//选择要使用的条形码类型
      width: 3,//设置条之间的宽度
      height: 100,//高度
      displayValue: false,//是否在条形码下方显示文字
      textAlign: "center",//设置文本的水平对齐方式
      textPosition: "bottom",//设置文本的垂直位置
      textMargin: 2,//设置条形码和文本之间的间距
      fontSize: 15,//设置文本的大小
      lineColor: "#000000",//设置条和文本的颜色。
      margin: 15, //设置条形码周围的空白边距
    });
  }

  tableChangeDectction(): void {
    // 改变引用触发变更检测。
    this.dataList = [...this.dataList];
    this.cdr.detectChanges();
  }

  tableLoading(isLoading: boolean): void {
    this.tableConfig.loading = isLoading;
    this.tableChangeDectction();
  }

  changePageSize(e: number): void {
    this.tableConfig.pageSize = e;
  }


  templateDown(): void {
    this.dataService.getLabelTemplate().subscribe(res => {
      const blob = new Blob([res], {type: 'text/plain;charset=utf-8'});
      FileSaver.saveAs(blob, `标准模板下载.xlsx`);
    });
  }

  importResult(): void {
    this.getDataList();
  }

  exportResult(): void {
    const params: SearchCommonVO<any> = {
      pageSize: 0,
      pageNum: 0,
      filters: this.searchParam!
    };
    this.dataService.getExportData(params).subscribe(res => {
      const blob = new Blob([res], {type: 'text/plain;charset=utf-8'});
      FileSaver.saveAs(blob, `导出数据.xlsx`);
    });
  }

  add(): void {
    this.modalService.show({
      nzTitle: this.dragTpl,
      nzMask: false,
      nzMaskStyle: {display: 'none'}
    }).subscribe(({modalValue, status}) => {
      if (status === ModalBtnStatus.Cancel) {
        return;
      }
      this.tableLoading(true);
      this.addEditData(modalValue, 'addLabel');
    }, error => this.tableLoading(false));
  }

  del(id: number): void {
    this.modalSrv.confirm({
      nzTitle: '确定要删除吗？',
      nzContent: '删除后不可恢复',
      nzOnOk: () => {
        this.tableLoading(true);
        this.dataService.delLabel([id]).subscribe(() => {
          if (this.dataList.length === 1) {
            this.tableConfig.pageIndex--;
          }
          this.getDataList();
          this.checkedCashArray.splice(this.checkedCashArray.findIndex(item => item.id === id), 1);
        }, error => this.tableLoading(false));
      }
    });
  }

  edit(id: number): void {
    this.dataService.getLabelDetail({id: id, operationType: 1}).subscribe(res => {
      this.modalService.show({nzTitle: '编辑'}, res).subscribe(({modalValue, status}) => {
        if (status === ModalBtnStatus.Cancel) {
          return;
        }
        modalValue.id = id;
        this.tableLoading(true);
        this.addEditData(modalValue, 'editLabel');
      }, error => this.tableLoading(false));
    });
  }

  addEditData(param: ContractLabel, methodName: 'editLabel' | 'addLabel'): void {
    this.dataService[methodName](param).subscribe(() => {
      this.getDataList();
    });
  }

  browserPrint(id: number): void {
    this.toJsBarcode(id);
    const printContent = document.getElementById("jsbarcode")!.innerHTML;
    const WindowPrt = window.open('', '', 'left=0,top=0,toolbar=0,scrollbars=0,width=auto,status=0');
    WindowPrt!.document.write(printContent);
    WindowPrt!.document.close();
    WindowPrt!.focus();
    WindowPrt!.print();
    WindowPrt!.close();
  }

  ngOnInit(): void {
    this.initTable();
  }

  getScanDetail(e: any): void {
    if (e != null) {
      this.dataService.getLabelDetail({id: e, operationType: 1}).subscribe(res => {
        this.notification.template(this.template!, {nzData: res, nzDuration: 0, nzStyle: {width: '600px'}});
        this.uid = null;
      });
    }
  }

  getPrint(e: any): void {
    if (e != null) {
      this.dataService.getLabelDetail({id: e, operationType: 0}).subscribe(res => {
        this.detailData = res;
        this.cdr.detectChanges();
        const printContent = document.getElementById("scancode")!.innerHTML;
        const WindowPrt = window.open('', '', 'left=0,top=0,toolbar=0,scrollbars=0,width=auto,status=0');
        WindowPrt!.document.write(printContent);
        WindowPrt!.document.close();
        WindowPrt!.focus();
        WindowPrt!.print();
        WindowPrt!.close();
        this.id = null;
        this.getDataList();
      });
    }
  }

  getLabelsList(): Promise<void> {
    return new Promise<void>(resolve => {
      this.dataService.getTypeList({pageSize: 0, pageNum: 0}).subscribe(({list}) => {
        this.Options = [];
        list.forEach(({id, typeName}) => {
          const obj: OptionsInterface = {
            label: typeName,
            value: id!,
          };
          this.Options.push(obj);
        });
        resolve();
      });
    });
  }

  ngAfterViewInit(): void {
    this.getLabelsList();
    this.myInput.nativeElement.focus();
  }

  private initTable(): void {
    this.tableConfig = {
      showCheckbox: false,
      headers: [
        {
          title: '项目号+档案号',
          field: 'projectNum',
          tdClassList: ['text-wrap'],
          width: 200,
        },
        {
          title: '委托方',
          field: 'client',
          tdClassList: ['text-wrap'],
          width: 200,
        },
        {
          title: '项目内容',
          field: 'projectContent',
          tdClassList: ['text-wrap'],
          width: 230,
        },
        {
          title: '所属标签',
          field: 'typeName',
          tdClassList: ['text-wrap'],
          width: 100,
        },
        {
          title: '存档',
          field: 'repertoryFlag',
          pipe: 'repertoryFlag',
          tdTemplate: this.repertoryFlagTpl,
          width: 100,
        },
        {
          title: '存档日期',
          field: 'storageTime',
          pipe: 'date:yyyy-MM-dd',
          tdClassList: ['text-wrap'],
          width: 100,
        },
        {
          title: '评价师',
          field: 'evaluatePerson',
          width: 100,
        },
        {
          title: '借出',
          field: 'lendFlag',
          pipe: 'lendFlag',
          tdTemplate: this.lendFlagTpl,
          width: 100,
        },
        {
          title: '借出时间',
          field: 'lendTime',
          pipe: 'date:yyyy-MM-dd',
          tdClassList: ['text-wrap'],
          width: 100,
        },
        {
          title: '借出人',
          field: 'lendPerson',
          width: 100,
        },
        {
          title: '备注',
          field: 'remark',
          tdClassList: ['text-wrap'],
          width: 200,
        },
        {
          title: '签订人',
          field: 'signPerson',
          width: 100,
        },
        {
          title: '下任务时间',
          field: 'startTaskTime',
          pipe: 'date:yyyy-MM-dd',
          tdClassList: ['text-wrap'],
          width: 100,
        },
        {
          title: '操作',
          tdTemplate: this.operationTpl,
          width: 200,
          fixed: true
        }
      ],
      total: 0,
      loading: true,
      pageSize: 10,
      pageIndex: 1,
    };
  }

}
